/**
 * [1 Timothy 3:16-17 ESV]
 * All Scripture is breathed out by God and profitable
 * for teaching, for reproof, for correction, and for training in righteousness,
 * that the man of God may be complete, equipped for every good work.
 *
 * BibleReader is an simple application for you to study God's Word.
 * The main user of this application maybe the pastor who's main language
 * is Chinese.
 *
 * You can use it totally free, and if you want to get source code of
 * this application, please email me at dweng123@gmail to get the source
 * code.
 */
#include <QDir>
#include <QSettings>
#include <QFile>
#include <QObject>
#include <QtXml>
#include "biblecommentarydao.h"
#include "Logger.h"

BibleCommentaryDAO::BibleCommentaryDAO(QString &bc, QString &bcp)
{
    bcName = bc;
    bcPath = bcp;

    init();
}

BibleCommentaryDAO::~BibleCommentaryDAO()
{
}

BibleCommentaryInfo BibleCommentaryDAO::getCmtInfo()
{
    QString name;
    QString sql = "select * from info";
    query->exec(sql);
    //LOG_INFO() << sql;
    while (query->next()) {
        name = query->value(0).toString();
        //LOG_INFO() << name;
        if (name == "version") {
            bci.setVersion(query->value(1).toInt());
        } else if (name == "shortname") {
            bci.setShortname(query->value(1).toString());
            bci.setName(query->value(1).toString());
        } else if (name == "fullname") {
            bci.setFullname(query->value(1).toString());
        } else if (name == "copyright") {
            bci.setCopyright(query->value(1).toString());
        } else if (name == "lang") {
            bci.setLang(query->value(1).toString());
        } else if (name == "description") {
            bci.setDescription(query->value(1).toString());
        }
    }
    return bci;
}

QString BibleCommentaryDAO::getChapterCmt(int book, int chapter)
{
    QString sql = "select * from cmt where bookid=" + QString::number(book)
            + " and chapterid=" + QString::number(chapter);

    query->exec(sql);
    if (query->next()) {
        //LOG_INFO() << query->value(0).toInt() << ","<<query->value(1).toInt();
        return query->value(2).toString();
    } else {
        return QObject::tr("Sorry, there is no commentary on this chapter");
    }
}

bool BibleCommentaryDAO::deinit()
{
    if (cmtDB.isOpen()) {
        cmtDB.close();
    }

    return true;
}

bool BibleCommentaryDAO::init()
{
    if (QSqlDatabase::contains(bcName)) {
        cmtDB = QSqlDatabase::database(bcName);
    } else {
        cmtDB = QSqlDatabase::addDatabase("QSQLITE", bcName);
        cmtDB.setDatabaseName(bcPath);
    }

    if (!cmtDB.open()) {
        LOG_ERROR() << "Can not open database:" << bcName << "\n"
                    << cmtDB.lastError().text();
        return false;
    }

    query = new QSqlQuery(cmtDB);
    return true;
}
